package com.nowcoder.community.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;

@Slf4j
public class JsonBody extends HashMap<String, Object> {
    private static final ObjectMapper om = new ObjectMapper();

    public static JsonBody custom(int code, String msg) {
        JsonBody ret = new JsonBody();
        ret.put("code", code);
        if (msg != null) {
            ret.put("msg", msg);
        }
        return ret;
    }

    public static JsonBody ok(String msg) {
        return JsonBody.custom(0, msg);
    }

    public static JsonBody error(String msg) {
        return JsonBody.custom(500, msg);
    }

    public JsonBody set(String k, Object v) {
        super.put(k, v);
        return this;
    }

    public String toJson() {
        try {
            String ret;
            log.debug(ret = om.writeValueAsString(this));
            return ret;
        } catch (JsonProcessingException e) {
            log.error("JsonBody转Json字符串失败: " + e.getMessage());
            return null;
        }
    }
}
